﻿using AutoMapper.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Cyss.Core.Helper
{
    /// <summary>
    /// 
    /// </summary>
    public class XmlHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj, XmlSerializerNamespaces ns=null)
        {
            return Serialize<T>(obj, Encoding.UTF8, ns);
        }


        /// <summary>
        /// 实体对象序列化成xml字符串  
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="encoding"></param>
        /// <param name="ns"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj, Encoding encoding, XmlSerializerNamespaces ns)
        {
            try
            {

                if (obj == null)
                    throw new ArgumentNullException("obj");

                var ser = new XmlSerializer(obj.GetType());
                using (var ms = new MemoryStream())
                {
                    using (var writer = new XmlTextWriter(ms, encoding))
                    {
                        writer.Formatting = Formatting.Indented;
                        if (ns == null)
                        {
                            ser.Serialize(writer, obj);
                        }
                        else
                        {
                            ser.Serialize(writer, obj, ns);
                        }
                    }
                    var xml = encoding.GetString(ms.ToArray());
                    xml = xml.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
                    xml = xml.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
                    //xml = Regex.Replace(xml, @"\s{2}", "");
                    //xml = Regex.Replace(xml, @"\s{1}/>", "/>");
                    return xml;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>  
        /// 反序列化xml字符为对象，默认为Utf-8编码  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="xml"></param>  
        /// <returns></returns>  
        public static T DeSerialize<T>(string xml)
            where T : new()
        {
            xml = System.Text.RegularExpressions.Regex.Replace(xml, @"(xmlns:?[^=]*=[""][^""]*[""])", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
            xml = System.Text.RegularExpressions.Regex.Replace(xml, @"(ns\d:)", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
            xml = System.Text.RegularExpressions.Regex.Replace(xml, @"(xsi:?[^=]*=[""][^""]*[""])", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);

            return DeSerialize<T>(xml, Encoding.UTF8);
        }

        /// <summary>  
        /// 反序列化xml字符为对象  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="xml"></param>  
        /// <param name="encoding"></param>  
        /// <returns></returns>  
        public static T DeSerialize<T>(string xml, Encoding encoding)
            where T : new()
        {
            try
            {
                var mySerializer = new XmlSerializer(typeof(T));
                using (var ms = new MemoryStream(encoding.GetBytes(xml)))
                {
                    using (var sr = new StreamReader(ms, encoding))
                    {
                        return (T)mySerializer.Deserialize(sr);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }


        public static T XmlToObject<T>(string xml) where T : class
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);

            string nodeName = typeof(T).Name.ToFirstLower();
            var node = xmlDoc.SelectSingleNode(nodeName);
            if (node == null)
            {
                return null;
            }

            var model = System.Activator.CreateInstance<T>(); ;

            XmlNode(model, node);

            return model;
        }

        private static void XmlNode(object model, XmlNode node)
        {
            var propertyInfos = model.GetType().GetCacheNamedMemberAccessors();

            foreach (var pro in propertyInfos)
            {

                string nodeName = pro.ProjectName.ToFirstLower();

                if (pro.PropertyType.IsListType())
                {
                    var itemType = pro.PropertyType.GenericTypeArguments.FirstOrDefault();

                    string nodeItemName = itemType.Name.ToFirstLower();

                    XmlNodeList xmlNodeList = node.SelectNodes(nodeItemName);
                    if (xmlNodeList == null)
                    {
                        continue;
                    }

                    List<object> list = new List<object>();

                    foreach (XmlNode xmlNode in xmlNodeList)
                    {
                        var item = System.Activator.CreateInstance(itemType);
                        list.Add(item);
                        XmlNode(item, xmlNode);
                    }
                    pro.SetValue(model, list);
                }
                if (pro.PropertyType.IsValueType)
                {
                    var n = node.SelectSingleNode(nodeName);
                    if (n == null)
                    {
                        continue;
                    }
                    pro.SetValue(model, n.InnerText);
                }
                if (pro.PropertyType.IsAnsiClass)
                {
                    var xmlNode = node.SelectSingleNode(nodeName);
                    if (xmlNode == null)
                    {
                        continue;
                    }
                    var obj = System.Activator.CreateInstance(pro.PropertyType);

                    XmlNode(obj, xmlNode);

                    pro.SetValue(model, obj);
                }
            }
        }

    }
}
